<template>
	<view class="user">
		<view class="history">
			<h1>浏览记录</h1>
		</view>

		<view class="box">
			<view class="content">
				<view class="item" v-for="(item,index) in historyList" :key="item.id">
					<ListItem :item=item @click.native='openDetail(item)' page='user'></ListItem>
				</view>
			</view>
		</view>

		<view class="noHistory" v-if="!historyList.length">
			<view>
				没有浏览记录捏~~
			</view>
		</view>
	</view>
</template>

<script>
	import {
		parseTime
	} from '@/utils/time.js';
	export default {
		data() {
			return {
				historyList: [],
			};
		},
		onShow() {
			this.getHistoryData()
		},
		methods: {
			//从本地存储获取历史浏览记录数据
			getHistoryData() {
				let data = uni.getStorageSync('historyData') || [];
				this.historyList = data
			},
			//打开新闻详情
			openDetail(item) {
				this.saveHistory(item);
				uni.navigateTo({
					url: `../../pages/detail/detail?id=${item.id}&classid=${item.classid}`
				})
			},
			// 将浏览记录本地化存储
			saveHistory(item) {
				let historyData = uni.getStorageSync('historyData') || [];
				let index = historyData.findIndex(ele => ele.id == item.id)
				if (index != -1) {
					historyData.splice(index, 1)
				}
				item.historyTime = parseTime(Date.now())
				historyData.unshift(item)
				//最多保留十条历史数据
				if (historyData.length > 10) historyData.pop()
				uni.setStorageSync('historyData', historyData)
			}
		}
	}
</script>

<style lang="less" scoped>
	.user {
		.history {
			text-align: center;
		}

		.box {
			padding: 20rpx;
			padding-top: 120rpx;

			.content {

				// width: 100%;
				overflow: hidden;

				// padding-top: 120rpx;
				.item {
					padding: 20rpx;
					width: 100%;
					border-bottom: 1rpx dashed gray;
				}
			}
		}
	}
</style>
